package forum.dao;

import forum.model.Keyword;
import forum.util.DBUtil;
import lombok.SneakyThrows;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author haomin
 * @date 2022/07/04 10:11
 **/

public class KeyDao {

    // 插入查询的关键字
    @SneakyThrows
    public void insertKey (String keyword){
        String sql = "INSERT INTO `forum_management_information_system2`.`key` (`keyword`) VALUES (?);";
        try (Connection c = DBUtil.connection()){
            try (PreparedStatement ps = c.prepareStatement(sql)){
                ps.setString(1,keyword);

                ps.executeUpdate();
                System.out.println("插入完成");
            }
        }
    }

    // 更新主贴回复数
    @SneakyThrows
    public void updateTReplyCount(int tID, int count) {
        String sql = "update topic set tReplyCount = ? where tID = ?";
        try (Connection c = DBUtil.connection()) {
            try (PreparedStatement ps = c.prepareStatement(sql)) {
                ps.setInt(1,count);
                ps.setInt(2,tID);

                ps.executeUpdate();
            }
        }
    }

    // 查询是否存在关键字
    @SneakyThrows
    public String selectKey () {
        String sql = "select keyword from forum_management_information_system2.key;";
        try (Connection c = DBUtil.connection()){
            try (PreparedStatement ps = c.prepareStatement(sql)){
                try (ResultSet rs = ps.executeQuery()){
                    if(rs.next()){
                        String keyword = rs.getString("keyword");
                        return keyword;
                    }else {
                        return null;
                    }

                }
            }
        }
    }

    // 删除关键字
    @SneakyThrows
    public void deleteKey () {
        String sql = "DELETE FROM `forum_management_information_system2`.`key` WHERE (1 = 1);";
        try (Connection c = DBUtil.connection()){
            try (PreparedStatement ps = c.prepareStatement(sql)){
                ps.executeUpdate();
            }
        }
    }
}